package com.tange.ai.iot.client.gnssa.play.multi

import android.content.Context
import android.content.Intent
import android.graphics.*
import android.os.Bundle
import android.view.Gravity
import android.widget.FrameLayout
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityDeviceLiveMultiChannelBinding
import com.tange.base.toolkit.*
import com.tange.core.device.facade.ConnectStatus
import com.tange.core.device.facade.DeviceFacade
import com.tange.core.device.facade.Status
import com.tange.core.media.render.DeviceMediaRender
import com.tange.core.media.source.impl.live.ChannelDeviceLiveMediaSource
import com.tange.core.media.source.impl.live.DeviceLiveMediaSource
import com.tange.core.trouble.shooting.entry.DebuggingAssistant
import com.tange.core.universal.instructions.BatteryStrategyInstruction
import com.tg.appcommon.android.TGLog
import com.tg.data.media.AvSyncController

/**
 * 多视频通道的设备直播页面展示（多路视频使用 不同通道 进行传输）
 *
 * 此处 演示 2 个通道（画中画设备）
 *
 * 注意：仅演示视频播放，其余截屏等功能参考 DeviceLiveActivity
 */
class MultiChannelDeviceLiveActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MultiChannelDeviceLiveActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, MultiChannelDeviceLiveActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private lateinit var deviceId: String

    private lateinit var binding: ActivityDeviceLiveMultiChannelBinding

    private lateinit var deviceFacade: DeviceFacade

    /**
     * 视频通道-1
     */
    private lateinit var deviceLiveMediaSource_1: DeviceLiveMediaSource
    private lateinit var deviceMediaRender_1: DeviceMediaRender

    /**
     * 视频通道-2
     */
    private lateinit var deviceLiveMediaSource_2: DeviceLiveMediaSource
    private lateinit var deviceMediaRender_2: DeviceMediaRender

    private var rendered = false

    private lateinit var connectStatusObserver : Consumer<ConnectStatus>
    private var avSyncController : AvSyncController = AvSyncController()

    // 是否以单画面的形式展示
    private var singeDisplayMode = false
    private var currentDisplayCameraIndex = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDeviceLiveMultiChannelBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            com.tange.ai.iot.client.gnssa.utils.Utils.setDarkStatusBar(this@MultiChannelDeviceLiveActivity, Color.TRANSPARENT)
        }

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)!!

        // 初始化调试助手，设置 顶部的 标题 为触发入口
        DebuggingAssistant.attach(this, binding.name).apply {
            deviceId = this@MultiChannelDeviceLiveActivity.deviceId
        }


        connectStatusObserver = Consumer<ConnectStatus> {
            TGLog.i(TAG, "[connect-status] ${it.status}")
            ui {
                if (it.status != Status.SUCCESS) {
                    if (it.status == Status.DISCONNECTED_BY_DEVICE) {
                        Tips.show("设备侧主动断开了连接，将在3秒后自动关闭页面")
                        binding.loading.postDelayed({
                            finish()
                        }, 3000L)
                    } else if (it.status == Status.FAILED) {
                        binding.loading.gone()
                        binding.connect.visible()
                        binding.connect.text = "重试"
                        Tips.show("连接失败：$it")
                    } else {
                        binding.loading.visible()
                    }
                } else {
                    if (rendered) {
                        binding.loading.gone()

                    }
                }
            }
            if (it.status == Status.SUCCESS) {
//                getBatteryStrategyInstruction()
            }
        }

        // 创建设备交互模块
        deviceFacade = DeviceFacade(deviceId).apply {

            // 监听连接状态变化
            observeConnectStatus(connectStatusObserver)
        }

        configureVideoChannel_1()
        configureVideoChannel_2()


        binding.loading.visible()
        binding.audio.onClicked { switchAudio() }
        binding.back.onClicked { finish() }
        binding.connect.onClicked {
            binding.connect.gone()
            deviceFacade.connect()
        }

        binding.resolutions.visible()
        binding.resolutions.onClicked { queryResolutions() }

        binding.card.onClicked { MultiChannelDevicePlaybackActivity.launch(it.context, deviceId) }
        binding.cloud.onClicked { MultiChannelCloudPlaybackActivity.launch(it.context, deviceId) }

        binding.switchDisplayMode.onClicked { onDisplayModeSwitch() }
        binding.switchCameraIndex.onClicked { onSwitchCameraIndex() }
    }

    private fun getBatteryStrategyInstruction(){
        var batteryStrategy = BatteryStrategyInstruction(deviceFacade)
        batteryStrategy.current{
            var hour = it.data?.plans?.get(0)?.to?.hour
            it.data?.plans?.get(0)?.to?.hour = (2+ hour!!).toByte()
            it.data?.let { it1 ->
                batteryStrategy.update(it1){
                    TGLog.i(TAG,"BatteryPowerStrategyInstruction_ ${it}")
                }
            }
        }
    }
    // 切换所展示的摄像头画面
    private fun onSwitchCameraIndex() {

        deviceMediaRender_1.detach()
        deviceMediaRender_2.detach()

        if (currentDisplayCameraIndex == 0) {
            switchToCamera1()
        } else {
            switchToCamera0()
        }
    }

    private fun switchToCamera0() {
        currentDisplayCameraIndex = 0
        deviceMediaRender_1.attach(binding.playerContainer1, createCenterLayoutParams())
        deviceMediaRender_1.apply {
            observeFirstFrameRendered {
                Tips.show("切换成功，当前为画面1")
            }
        }
    }

    private fun switchToCamera1() {
        currentDisplayCameraIndex = 1
        deviceMediaRender_2.attach(binding.playerContainer1, createCenterLayoutParams())
        deviceMediaRender_2.apply {
            observeFirstFrameRendered {
                Tips.show("切换成功，当前为画面2")
            }
        }
    }

    private fun onDisplayModeSwitch() {
        deviceMediaRender_1.detach()
        deviceMediaRender_2.detach()

        if (singeDisplayMode) {
            Tips.show("已切换为双画面模式")
            binding.switchDisplayMode.text = "切换为单画面模式"
            binding.switchCameraIndex.gone()
            deviceMediaRender_1.attach(binding.playerContainer1, createCenterLayoutParams())
            deviceMediaRender_2.attach(binding.playerContainer2, createCenterLayoutParams())
            deviceMediaRender_2.apply {
                observeFirstFrameRendered {
                }
            }
            deviceMediaRender_1.apply {
                observeFirstFrameRendered {
                }
            }
        } else {
            Tips.show("已切换为单画面模式")
            binding.switchDisplayMode.text = "切换为双画面模式"
            binding.switchCameraIndex.visible()
            currentDisplayCameraIndex = 0
            switchToCamera0()
        }
        singeDisplayMode = !singeDisplayMode
    }

    /**
     * 配置视频通道-1
     */
    private fun configureVideoChannel_1() {
        // 创建实时媒体数据源
        deviceLiveMediaSource_1 = ChannelDeviceLiveMediaSource(deviceFacade).apply {
            // 主通道一般采用默认 videoChannel 与 cameraIndex 即可，无需指定，除非设备修改了。

            observeAudioFrame {
                TGLog.i(TAG, "[configureVideoChannel_1_aa] ")
            }
        }

        // 创建媒体播放器
        deviceMediaRender_1 = DeviceMediaRender(this, deviceLiveMediaSource_1).apply {

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer1, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                TGLog.i(TAG, "[first-rendered] ")
                rendered = true
                binding.loading.gone()
            }
            setAvSyncController(avSyncController)
            mute(true) // 关闭声音播放
            // videoCapabilityEnable = true
        }
    }

    /**
     * 配置视频通道-2
     */
    private fun configureVideoChannel_2() {
        // 创建实时媒体数据源
        deviceLiveMediaSource_2 = ChannelDeviceLiveMediaSource(deviceFacade).apply {
            videoTransportChannel = 0x06 // 视频传输通道号，由设备端指定
            cameraIndex = 1 // 摄像头编号，与上述通道号应当为对应关系。第一个是0，第二个是1，依次递增。
        }

        // 创建媒体播放器
        deviceMediaRender_2 = DeviceMediaRender(this, deviceLiveMediaSource_2).apply {

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer2, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                TGLog.i(TAG, "[first-rendered] ")
                rendered = true
                binding.loading.gone()
            }

            // 针对副通道，关闭声音播放
            enableAudio(false)
            setAvSyncController(avSyncController)
        }
    }

    private fun queryResolutions() {
        deviceLiveMediaSource_1.querySupportedResolutions {
            ui {
                if (it.success) {
                    val resolutions = it.data!!
                    val currentResolution = deviceLiveMediaSource_1.currentVideoResolution()
                    var currentIndex = 0
                    resolutions.forEachIndexed { index, liveResolutions ->
                        if (liveResolutions.value == currentResolution) {
                            currentIndex = index
                        }
                    }
                    val items = Array(resolutions.size) { index -> if (index == currentIndex) "${resolutions[index].label} [当前]" else resolutions[index].label }

                    AlertDialog.Builder(this@MultiChannelDeviceLiveActivity)
                        .setTitle("选择视频码流")
                        .setItems(items) { _, which ->
                            run {
                                Tips.show("切换至 ${resolutions[which].label} ...")

                                // 为每一个视频通道都切换清晰度
                                deviceLiveMediaSource_1.switchVideoResolution(resolutions[which].value)
                                deviceLiveMediaSource_2.switchVideoResolution(resolutions[which].value)
                            }
                        }
                        .create()
                        .show()

                } else {
                    Tips.show("查询码流设置失败 ${it.message}")
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        TGLog.i(TAG, "[onResume] ")

            deviceLiveMediaSource_1.enableProduce(true)
            deviceMediaRender_1.play(true)

            deviceLiveMediaSource_2.enableProduce(true)
            deviceMediaRender_2.play(true)
        }

    override fun onPause() {
        super.onPause()
        TGLog.i(TAG, "[onPause] ")

        deviceLiveMediaSource_1.enableProduce(false)
        deviceMediaRender_1.play(false)

        deviceLiveMediaSource_2.enableProduce(false)
        deviceMediaRender_2.play(false)
    }

    override fun onDestroy() {
        super.onDestroy()
        deviceFacade.disconnect()
        deviceFacade.unObserveConnectStatus(connectStatusObserver)
    }

    private fun createCenterLayoutParams() = FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.MATCH_PARENT,
        FrameLayout.LayoutParams.MATCH_PARENT
    ).apply { gravity = Gravity.CENTER }

    private fun switchAudio() {
        if (!deviceMediaRender_1.muted) {
            binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_off_24))
            deviceMediaRender_1.mute(true)
        } else {
            binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_on_24))
            deviceMediaRender_1.mute(false)
        }
    }
}